package com.example.musicplayer.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.example.musicplayer.R;
import com.example.musicplayer.adapter.PopUpMusicListAdapter;
import com.example.musicplayer.entity.Music;
import com.example.musicplayer.service.MusicService;

import java.util.List;

public class MusicPopUpWindow extends PopupWindow {
    private TextView mCloseMusicList;
    private RecyclerView mRecyclerView;
    private View mMenuView;
    private LinearLayoutManager mLinearLayoutManager;
    private List<Music> mMusics;

    @SuppressLint("InflateParams")
    public MusicPopUpWindow(Context context, MusicService.MusicBinder service) {
        super(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.pop_up_music_list, null);

        mLinearLayoutManager = new LinearLayoutManager(mMenuView.getContext());
        mCloseMusicList = mMenuView.findViewById(R.id.close_music_list);
        mRecyclerView = mMenuView.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mMusics = service.getMusicList();
        PopUpMusicListAdapter adapter = new PopUpMusicListAdapter(context, mMusics);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setItemViewCacheSize(500);

        mCloseMusicList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        this.setContentView(mMenuView);
        this.setWidth(RecyclerView.LayoutParams.MATCH_PARENT);
        this.setHeight(1400);
        this.setFocusable(true);
        this.setAnimationStyle(R.style.Animation_Design_BottomSheetDialog);
        ColorDrawable drawable = new ColorDrawable(Color.WHITE);
        this.setBackgroundDrawable(drawable);
        mMenuView.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int height = mMenuView.findViewById(R.id.music_list_top).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });
    }
}
